import React, { Component } from 'react';
import './Gwc.scss'
import { NavBar, Empty, Button, Checkbox, Modal, Toast } from 'antd-mobile'
import * as service from '../../api'

class cate extends Component {
    constructor(props) {
        super(props)
        this.state = {
            arr: [],
            code: '',
        }
    }
    toshouye() {
        this.props.history.push('/index/home')
    }
    // 初次渲染
    componentDidMount() {
        if (!window.localStorage.getItem('token')) {
            this.props.history.replace('/login')
        }
        this.xuanran()
    }
    // 重新渲染页面
    async xuanran() {
        var res = await service.cart_list({ userid: window.localStorage.getItem('userid') })
        // console.log(res);
        this.setState({
            arr: res.data.data,
            code: res.data.code
        })
    }
    // 清空购物车
    async qingkong() {
        var res = await service.cart_removeall({ userid: window.localStorage.getItem('userid') })
        // console.log(res);
        this.xuanran()
    }
    //数量减一
    async numjian(item) {
        if (item.num > 1) {
            var res = await service.cart_updatenum({ cartid: item.cartid, num: item.num - 1 })
            // console.log(res);
            this.xuanran()
        }
        else if (item.num == 1) {
            const result = await Modal.confirm({
                content: '确定移除该商品?',
            })
            if (result) {
                var res = await service.cart_remove({ cartid: item.cartid })
                this.xuanran()
                // console.log(res);
                Toast.show({ content: '移除成功', position: 'center', icon: 'success' })

            } else {
                Toast.show({ content: '取消成功', position: 'center', icon: 'success' })
            }
        }
    }
    // 数量加一
    async numadd(item) {
        var res = await service.cart_updatenum({ cartid: item.cartid, num: item.num + 1 })
        // console.log(res);
        this.xuanran()
    }
    //更新商品选中状态
    async handleChange(cartid, flag) {
        var newflag = !flag
        var res = await service.cart_selectone({ cartid, flag: newflag })
        // console.log(res);
        if (res.data.code == 200) {
            this.xuanran();
            Toast.show({
                icon: 'success',
                content: '更新商品状态成功',
            })
        }
    }
    // 全选状态
    async handleAllchange() {
        var { arr } = this.state;
        var all_checked = arr.every(item => item.flag);
        arr.forEach(item => {
            item.flag = !all_checked;
        });
        this.setState({ arr });
        var userid = window.localStorage.getItem('userid')
        var res = await service.cart_selectall({ userid, type: !all_checked })
        if (res.data.code === "200") {
            Toast.show({
                icon: 'success',
                content: res.data.message,
            })
        } else {
            Toast.show({
                icon: 'fail',
                content: res.data.message,
            })
        }

    }
    xiadan() {
        Toast.show({ content: '下单', position: 'center' })
    }
    totalPrice() {
        return this.state.arr.reduce((t, item) => {
            return item.flag ? t + item.originprice * item.num : t + 0;
        }, 0);
    }
    render() {
        return (
            <div className='gwc'>
                <NavBar style={{
                    '--height': '50px',
                    '--border-bottom': '1px #eee solid',
                }} backArrow={false} right={<div onClick={() => { this.qingkong() }}>清空</div>}>购物车
                </NavBar>
                {
                    this.state.code == 200 &&
                    <div className="center">
                        {
                            this.state.arr.map((item, index) => {
                                return (
                                    < div className="shoplist" key={index}>
                                        <div>
                                            <Checkbox checked={item.flag} onChange={() => { this.handleChange(item.cartid, item.flag) }} />
                                        </div>
                                        <img src={item.img1} alt="" />
                                        <div className='shangping'>
                                            <div className="p1">{item.proname}</div>
                                            <div className="shopbottom">
                                                <p id='p2'>￥{item.originprice}</p>
                                                <div className="right">
                                                    <button onClick={() => { this.numjian(item) }}>-</button>
                                                    &nbsp;{item.num} &nbsp;
                                                    <button onClick={() => { this.numadd(item) }}>+</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                )
                            })
                        }

                        <div className="tijiao">
                            <div className="tijiaoleft">
                                <Checkbox checked={this.state.arr.every(item => item.flag)} onChange={this.handleAllchange.bind(this)} />&nbsp;全选
                            </div>
                            <div className="tijiaoright">
                                合计：&nbsp;<div className='price'>￥{this.totalPrice().toFixed(2)}</div>&emsp; <Button shape='rounded' size='middle' color='danger' onClick={this.xiadan}>
                                    提交订单
                                </Button>
                            </div>
                        </div>
                    </div>
                }
                {
                    this.state.code != 200 &&
                    <div className="bottom">
                        <Empty
                            style={{ padding: '64px 0' }}
                            imageStyle={{ width: 128 }}
                            description='购物车空空如也'
                        />
                        <Button shape='rounded' size='mini' color='primary' onClick={() => { this.toshouye() }}>
                            去逛逛
                        </Button>
                    </div>
                }

                {
                    this.state.code != 200 &&
                    <div className="tijiao">
                            <div className="tijiaoleft">
                                <Checkbox/>&nbsp;全选
                            </div>
                            <div className="tijiaoright">
                                合计：&nbsp;<div className='price'>￥0.00</div>&emsp; <Button shape='rounded' size='middle' color='danger' onClick={this.xiadan}>
                                    提交订单
                                </Button>
                            </div>
                        </div>
                }
            </div >
        );
    }
}

export default cate;